package top.wangjiu.reactive.rpc.handler;

import top.wangjiu.reactive.rpc.model.RpcRequest;
import top.wangjiu.reactive.rpc.model.RpcResponse;

import java.util.concurrent.CompletableFuture;

/**
 * @ClassName DefaultResultTypeHandler
 * @Description TODO
 * @Author wangjiu
 * @Date 2021/8/3 5:05 下午
 */
public class FutureRequestHandler extends AbstractRequestHandler<CompletableFuture> {

    private volatile String requestId;

    private volatile CompletableFuture res;

    @Override
    public void onRequest(RpcRequest request) {
        if(requestId == null){
            requestId = request.getRequestId();
            RpcResponse response = new RpcResponse(requestId);
            response.setFirst(true);
            response.setLast(true);
            try {
                res = invoke(request);
                res.whenComplete((r,e)->{
                    if(e!=null){
                        response.setSuccess(false);
                        response.setCause((Throwable) e);
                    }else {
                        response.setResult(r);
                    }
                    write(response);
                });
            } catch (Exception e) {
                response.setSuccess(false);
                response.setCause(e);
                write(response);
            }
        }else{

        }
    }

    @Override
    public void onDisconnect() {
        if(res != null){
            res.cancel(true);
        }
    }
}
